﻿using System;
using System.Collections.Generic;
using System.Text;
using Windvoice.Blog.Model;
using System.Data;
using System.Configuration;
using Windvoice.Util;

namespace Windvoice.Blog.DataAccess
{
    public class CommentDAL
    {
        private string ConnectionString = ConfigurationManager.ConnectionStrings["windvoice"].ToString();

        public int Comment_Insert(CommentInfo comment)
        {
            string f = "INSERT INTO [Comment] ([author],[authorid],[content],[time],[ip],[articleid]) VALUES ('{0}','{1}','{2}','{3}','{4}',{5})";
            string command = String.Format(f,comment.Author,comment.AuthorID,comment.Content,comment.Time,comment.IP,comment.ArticleID);
            return AccessHelper.ExecuteNonQuery(ConnectionString,command);
        }

        public int Comment_Reply(CommentInfo comment)
        {
            string f = "UPDATE [Comment] SET reply='{0}',replyauthor='{1}',replytime='{2}',replyip='{3}' WHERE [id]={4}";
            string command = String.Format(f,comment.Reply,comment.ReplyAuthor,comment.ReplyTime,comment.ReplyIP,comment.ID);
            return AccessHelper.ExecuteNonQuery(ConnectionString,command);
        }

        public int Comment_Delete(int CommentID)
        {
            string command = "DELETE FROM [Comment] WHERE [id]="+CommentID.ToString();
            return AccessHelper.ExecuteNonQuery(ConnectionString,command);
        }

        public DataTable Comment_GetList()
        {
            string command = "SELECT * FROM [Comment] ORDER BY [id] DESC";
            return AccessHelper.ExecuteDataSet(ConnectionString, command).Tables[0];
        }

        public DataTable Comment_GetList(int ArticleID)
        {
            string command = "SELECT * FROM [Comment] WHERE [articleid]=" + ArticleID.ToString()+" ORDER BY [id] ASC";
            return AccessHelper.ExecuteDataSet(ConnectionString,command).Tables[0];
        }

        public int Comment_GetCommentCount(int ArticleID)
        {
            string command = "SELECT count(0) FROM [Comment] WHERE [articleid]="+ArticleID.ToString();
            return (int)AccessHelper.ExecuteScaler(ConnectionString,command);
        }

        public CommentInfo Comment_Get(int CommentID)
        {
            string command = "SELECT * FROM [Comment] WHERE [id]="+CommentID.ToString();
            DataTable dt = AccessHelper.ExecuteDataSet(ConnectionString, command).Tables[0];

            CommentInfo comment=null;

            if (dt.Rows.Count > 0) comment = new CommentInfo(dt.Rows[0]);

            return comment;
        }
    }
}
